#include "TaskThread.h"
#include "../Utils/LogUtil.h"
#include "../Core/CoreGlobals.h"

TaskThread::TaskThread() :
	mThread(nullptr),
	mMalloc(nullptr),
	mQuitForReturn(false)
{

}

uint32 TaskThread::Setup(const TCHAR* threadName, ThreadPriority threadPriority)
{
	mThread = RunnableThread::Create(this, threadName, threadPriority);
	return mThread->GetThreadID();
}

void TaskThread::Kill()
{
	mThread->Kill(true);
}

bool TaskThread::Init()
{
	mMalloc = new MallocExclusive();
	return mMalloc != nullptr;
}

void TaskThread::Stop()
{
	RequestReturn();
}

void TaskThread::Exit()
{
	delete mMalloc;
	mMalloc = nullptr;
}

void TaskThread::ProcessTasksUntilReturn()
{
	while (!mQuitForReturn && mQueueTasks.Size() > 0)
	{
		BaseGraphTask* task = nullptr;
		mQueueTasks.Pop(&task);
		if (task != nullptr)
		{
			task->ExecuteTask();
		}
	}
}

void TaskThread::EnqueueTask(BaseGraphTask* task)
{
	// No enough capacity
	assert(mQueueTasks.Push(task));
}

void TaskThread::RequestReturn()
{
	mQuitForReturn = true;
}
